package com.sk.waste.app.utils

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.Settings
import androidx.activity.result.ActivityResultLauncher
import androidx.core.content.FileProvider
import com.lc.smc.lib.interfaces.LCInterface
import com.lc.smc.lib.utils.LCBaseUtil
import com.lc.smc.lib.utils.LCDialogUtil
import com.lc.smc.lib.utils.LCFileUtil
import com.lc.smc.lib.utils.LCLogger
import com.lc.smc.lib.utils.LCSPUtil
import com.lc.smc.lib.utils.ProgressUtil
import com.sk.waste.app.BuildConfig
import com.sk.waste.app.config.AppConfig
import com.sk.waste.app.config.NetWorkConfig
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
import org.json.JSONObject
import java.io.File
import java.io.IOException
import java.io.InputStream

/**
 *  @time 2024/10/30  14:05
 *  @author Im_jingwei
 *  @desc 更新
 */
object UpdateUtil {
    private val TAG = "LCLOG_UPDATE"
//    private var fileDirect = Environment.getExternalStorageDirectory().absolutePath + AppConfig.APPDIR_EXTERNAL_ROOT
    private var fileDirect = ""
    private var progressDialog: ProgressUtil? = null

    /**
     *  @time 2024/10/30  15:54
     *  @author Im_jingwei
     *  @desc 跳转手动开启安装权限页面
     */
    fun checkSetting(context: Activity, resultLaucher: ActivityResultLauncher<Intent>) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //权限没有打开，跳转界面，提示用户去手动打开
            val intent = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:" + context.packageName))
            resultLaucher.launch(intent)
        } else {
            //开始下载安装
//            download(context)
        }
    }

    /**
     *  @time 2024/10/30  15:29
     *  @author Im_jingwei
     *  @desc 检查更新
     */
    fun checkUpdate(context: Activity, isShowProgress: Boolean) {
        showProgressDialog(context, "检查更新中，请稍后...", isShowProgress)
        fileDirect = context.filesDir.absoluteFile.absolutePath.toString() + AppConfig.APPDIR_EXTERNAL_ROOT
        val file = File(fileDirect + AppConfig.APPDIR_EXTERNAL_CONFIG)
        if (!file.exists()) {
            file.mkdirs()
        }
        OkHttpUtil().httpRequestGet(NetWorkConfig.NET_URL_APPUPDATE, LCSPUtil[context, AppConfig.SP_ACCESS_TOKEN], object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                e.message?.let { LCLogger.d(TAG, it) }
                cancleProgressDialog()
            }

            override fun onResponse(call: Call, response: Response) {
                cancleProgressDialog()
                val body = response.body()!!.string()
                val jsonObject = JSONObject(body)
                if (body != null) {
                    NetWorkConfig.NET_URL_APP_DOWNLOAD = jsonObject.getString("app_download_url")
                    val versionName = jsonObject.getString("app_version")
                    val versionCode = jsonObject.getInt("version_code")
                    val forcedUpdating = jsonObject.getBoolean("forced_updating")
                    if (BuildConfig.VERSION_CODE < versionCode) {
                        context.runOnUiThread { showDialog(context, versionName, forcedUpdating) }
                    } else {
                        if (isShowProgress) {
                            LCBaseUtil.showToast(context, "当前版本已是最新版本！")
                        }
                    }
                } else {
                    if (isShowProgress) {
                        cancleProgressDialog()
                    }
                    LCBaseUtil.showToast(context, "检查更新出错，出错原因：${response.message()}")
                }
            }
        })
    }

    /**
     *  @time 2024/10/10  16:23
     *  @author Im_jingwei
     *  @desc 提示
     */
    @SuppressLint("UseCompatLoadingForDrawables")
    private fun showDialog(context: Activity, version: String, isForced: Boolean) {
        val dialog = LCDialogUtil(context)
        var msg = ""
        if (isForced) {
            msg = "检测到服务器有新版本存在\n版本: ${BuildConfig.VERSION_NAME} -> ${version}\n请更新后使用！"
        } else {
            msg = "检测到服务器有新版本存在\n版本: ${BuildConfig.VERSION_NAME} -> ${version}\n是否更新？"
        }
        dialog.setTileAndContent("系统更新提示", msg)
        dialog.setButtonOnclickListener { download(context) }
        dialog.setButtonOnclickListener(object : LCInterface.LcOnPnButtonClickLitener {
            override fun onNegetiveClick(vararg args: Any?) {

            }

            override fun onPositiveClick(vararg args: Any?) {
                download(context)
            }
        })
        if (isForced) {
            dialog.show()
        } else {
            dialog.showExpand()
        }
    }

    /**
     *  @time 2024/10/30  15:29
     *  @author Im_jingwei
     *  @desc 下载
     */
    fun download(context: Activity) {
        showProgressDialog(context, "开始下载最新版本,请稍后...", true)
        val file = File(fileDirect + AppConfig.APPDIR_EXTERNAL_APKS)
        if (!file.exists()) {
            file.mkdirs()
        }
        OkHttpUtil().httpRequestGet(NetWorkConfig.NET_URL_APP_DOWNLOAD, LCSPUtil[context, AppConfig.SP_ACCESS_TOKEN], object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                e.message?.let { LCLogger.d(TAG, it) }
                cancleProgressDialog()
                LCBaseUtil.showToast(context, "更新出错，请重试！")
            }

            override fun onResponse(call: Call, response: Response) {
                var inputStream: InputStream? = response.body()?.byteStream();
                if (response.code() == 200 && null != inputStream) {
                    LCFileUtil.instance.saveFile(
                        fileDirect + AppConfig.APPDIR_EXTERNAL_APKS, "fjzbxxpt.apk", inputStream,
                        object : LCInterface.LcFileSaveCallBackListener {
                            override fun onBackListener(success: Boolean?, msg: String?, path: String?) {
                                cancleProgressDialog()
                                if (success == true && path != null) {
                                    installApk(context, path)
                                    LCBaseUtil.showToast(context, "下载完成，开始安装...")
                                } else {
                                    LCBaseUtil.showToast(context, "apk安装失败，失败原因：" + msg)
                                }
                            }
                        })
                } else {
                    cancleProgressDialog()
                    LCBaseUtil.showToast(context, "下载出错，出错原因：${response.message()}")
                }
            }
        })
    }


    /**
     *  @time 2024/10/30  15:45
     *  @author Im_jingwei
     *  @desc 安卓apk
     */
    private fun installApk(context: Activity, path: String) {
        val intent = Intent(Intent.ACTION_VIEW)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        val file = Uri.parse(path).path?.let { File(it) }
        intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
        val uri = FileProvider.getUriForFile(context, "${BuildConfig.APPLICATION_ID}.fileprovider", file!!)
        intent.setDataAndType(uri, "application/vnd.android.package-archive")
        context.startActivity(intent)
    }


    /**
     * 显示交互弹窗(默认不可以点击弹窗外侧取消)
     * @param text 弹窗提示语
     */
    fun showProgressDialog(context: Activity, text: String?, isShow: Boolean) {
        if (!isShow) {
            return
        }
        if (progressDialog == null)
            progressDialog = ProgressUtil(context)
        progressDialog!!.setText(text)
        progressDialog!!.setCancelable(false)
        progressDialog!!.show()
    }

    fun cancleProgressDialog() {
        progressDialog?.cancel()
    }

}